export default {
	data() {
		return {
			title: '收银台',
			type: 'goods',
			goodsData: {},
			orderData: {
				goods_num: 0,
				pay_money: 0,
				goods_list: [],
				remark: '',
				create_time: 0
			},
			remark: '',
			outTradeNo: '',
			orderId: 0,
			searchType: 'mobile',
			searchText: '',
			searchTypeList: [{
					'label': '手机号',
					'value': 'mobile',
					'disabled': false
				},
				{
					label: '卡号',
					value: 'member_code',
					disabled: false
				},
				{
					'label': '昵称',
					'value': 'nickname',
					'disabled': false
				}
			],
			date: '',
			goodsIds: [],
			ordertime: '',
			scanCode: {
				code: '',
				lastTime: 0
			},
			isRepeat: false,
			isScanTrigger: false, // 扫码枪是否触发
			pageActive: '', // 记录当前页面活跃值
			leftIndexFocus: -1, // 左侧订单项 焦点索引
			rightIndexFocus: -1 // 右侧选择商品 焦点索引
		}
	},
	onShow() {
		this.orderData.create_time = this.$util.timeFormat(parseInt(new Date().getTime() / 1000));
		this.addScancodeEvent();
		if (this.$refs.goods) this.$refs.goods.init();
	},
	onHide() {
		this.removeScancodeEvent();
	},
	onLoad() {},
	methods: {
		switchStoreAfter() {
			this.wholeOrderCancel(true);
		},
		openMember() {
			if (this.$refs.selectMember) {
				this.pageActive = 'ShowMember';
				this.$refs.selectMember.open(() => {
					this.pageActive = 'ShowMemberAfter';
				});
			}
		},
		showMember() {
			this.pageActive = 'ShowMember';
			if (!this.memberInfo) {
				if (this.$refs.selectMember) this.$refs.selectMember.open(() => {
					this.type = 'member';
					this.pageActive = 'ShowMemberAfter';
				});
			} else {
				this.type = 'member';
				this.pageActive = 'ShowMemberAfter';
			}
		},
		showMemberCard() {
			this.pageActive = 'ShowMemberCard';
			if (!this.memberInfo) {
				if (this.$refs.selectMember) this.$refs.selectMember.open(() => {
					this.type = 'card';
					this.pageActive = 'ShowMemberCardAfter';
				});
			} else {
				this.type = 'card';
				this.pageActive = 'ShowMemberCardAfter';
			}
		},
		searchMember() {
			if (!this.searchText) {
				this.$util.showToast({
					title: '请输入会员信息',
					icon: 'error'
				});
				return false;
			}
			this.$refs.member.searchMemberByType(this.searchText, this.searchType);
		},
		switchType(index, item) {
			this.searchType = item.value;
		},
		addmember() {
			this.type = 'member';
			this.$refs.member.type = 'addmember';
		},
		/**
		 * 切换会员
		 */
		replaceMember() {
			if (this.$refs.member) this.$refs.member.memberId = 0;
			if (this.$refs.selectMember) this.$refs.selectMember.memberId = 0;
			this.$store.commit('setMemberInfo', null);
			let obj = {
				goods_num: 0,
				pay_money: 0,
				goods_list: [],
				remark: '',
				create_time: 0
			};
			Object.assign(this.orderData, obj);
			uni.setStorageSync('orderData', obj);
			this.type = !this.memberInfo ? 'goods' : 'member';
		},
		/**
		 * @param {Object} data
		 */
		selectGoods(data) {
			let key = 'sku_' + data.sku_id;
			let num = data.num || 1;
			num = parseInt(num);

			// 称重商品
			if (data.goods_class == 6) num = Number.parseFloat(data.weigh);

			// 已加入清单，追加数量
			if (this.goodsData[key]) {
				this.goodsData[key].num += num;
			} else {
				// 第一次加入清单，设置数据
				this.goodsData[key] = this.$util.deepClone(data);
				this.goodsData[key].num = num;
			}

			if (data.status && data.status == 'edit') {
				this.goodsData[key].num = num;
			}

			// 称重商品每次覆盖数量
			if (data.goods_class == 6) {
				this.goodsData[key].num = parseFloat(this.goodsData[key].num.toFixed(3))
			}

			// 调整单价
			if (data.adjust_price) {
				this.goodsData[key].price = parseFloat(data.adjust_price);
				this.goodsData[key].adjust_price = parseFloat(data.adjust_price);
			}
			this.goodsData[key].is_adjust = data.is_adjust || false;

			this.pageActive = 'SelectGoodsAfter'; // 记录页面当前活跃值：选择完商品

			this.scanCode = {
				lastTime: 0,
				code: ''
			}
			this.calculation();
		},
		selectMemberGoods(arr) {
			arr.forEach((data) => {
				let key = 'sku_' + data.sku_id + 'item_' + data.item_id;
				if (this.goodsData[key]) {
					this.goodsData[key].num += data.num;
				} else {
					this.goodsData[key] = data;
					this.goodsData[key].num = data.num;
				}
			})
			this.calculation();
		},
		deleteGoods(data) {
			if (data.card_item_id) {
				let _data = this.goodsData['sku_' + data.sku_id + 'item_' + data.card_item_id];

				this.$refs.member.memberCardData.list[_data.card_index].total_use_num -= _data.num;
				this.$refs.member.memberCardData.list[_data.card_index].item_list[_data.index].use_num -= _data.num;
				if (this.$refs.member.memberCardData.index == _data.card_index) {
					if (_data.card_type != 'timecard') this.$refs.member.memberCardData.currData.item_list[_data.index]
						.use_num -= _data.num;
					this.$refs.member.memberCardData.currData.total_use_num -= _data.num;
				}

				delete this.goodsData['sku_' + data.sku_id + 'item_' + data.card_item_id];
			} else {

				// 恢复调价
				for (let i = 0; i < this.$refs.goods.goodsData.list.length; i++) {
					let item = this.$refs.goods.goodsData.list[i];
					if (item.sku_id == data.sku_id) {
						item.adjust_price = item.price;
						item.adjust = {};
						break;
					}
				}
				delete this.goodsData['sku_' + data.sku_id];

			}

			this.calculation();

			if (!Object.keys(this.goodsData).length) {
				this.orderData.goods_list = [];
				this.orderData.goods_num = 0;
				this.orderData.pay_money = 0;
			}
		},
		// 清空
		clearGoods() {
			// 恢复调价
			for (let i = 0; i < this.$refs.goods.goodsData.list.length; i++) {
				let item = this.$refs.goods.goodsData.list[i];
				item.adjust_price = item.price;
				item.adjust = {};
			}
			this.goodsData = [];
			this.orderData.goods_list = [];
			this.orderData.goods_num = 0;
			this.orderData.pay_money = 0;
			this.goodsIds = [];
			uni.setStorageSync('orderData', "");
		},

		/**
		 * 商品数量增加
		 * @param {Object} data
		 */
		inc(data) {

			if (data.card_item_id) {
				let _data = this.goodsData['sku_' + data.sku_id + 'item_' + data.card_item_id],
					memberCardData = this.$refs.member.memberCardData;

				if (data.goods_type == '' && _data.num >= data.stock) {
					this.$util.showToast({
						title: '商品库存不足'
					});
					return;
				}

				// 如果会员卡项中正在变更的和该商品所使用的卡项一致
				if (memberCardData.index == _data.card_index && Object.keys(memberCardData.selected).length) return;

				if (_data.card_type == 'commoncard') {
					if (memberCardData.list[_data.card_index].total_num == memberCardData.list[_data.card_index]
						.total_use_num) return;
				} else if (_data.card_type != 'timecard') {
					if (memberCardData.list[_data.card_index].item_list[_data.index].num == memberCardData.list[_data
							.card_index].item_list[_data.index].use_num) return;
				}

				memberCardData.list[_data.card_index].total_use_num += 1;
				memberCardData.list[_data.card_index].item_list[_data.index].use_num += 1;

				if (memberCardData.index == _data.card_index) {
					memberCardData.currData.total_use_num += 1;
					if (_data.card_type != 'timecard') {
						memberCardData.currData.item_list[_data.index].use_num += 1;
					}
				}

				this.goodsData['sku_' + data.sku_id + 'item_' + data.card_item_id].num += 1;
			} else {
				let _data = this.goodsData['sku_' + data.sku_id];
				if (data.goods_type == '' && _data.num >= data.stock) {
					this.$util.showToast({
						title: '商品库存不足'
					});
					return;
				}
				this.goodsData['sku_' + data.sku_id].num += 1;
			}
			this.calculation();
		},
		/**
		 * 商品数量减少
		 * @param {Object} data
		 */
		dec(data) {
			if (data.card_item_id) {
				let _data = this.goodsData['sku_' + data.sku_id + 'item_' + data.card_item_id];
				if (_data.num == 1) return;

				this.$refs.member.memberCardData.list[_data.card_index].total_use_num -= 1;
				this.$refs.member.memberCardData.list[_data.card_index].item_list[_data.index].use_num -= 1;
				if (this.$refs.member.memberCardData.index == _data.card_index) {
					this.$refs.member.memberCardData.currData.item_list[_data.index].use_num -= 1;
					this.$refs.member.memberCardData.currData.total_use_num -= 1;
				}
				this.goodsData['sku_' + data.sku_id + 'item_' + data.card_item_id].num -= 1;
				this.calculation();
			} else {
				if (this.goodsData['sku_' + data.sku_id].num == 1) return;

				this.goodsData['sku_' + data.sku_id].num -= 1;
				this.calculation();
			}
		},
		/**
		 * 计算
		 */
		calculation() {
			this.goodsIds = [];
			if (!Object.keys(this.goodsData).length) {
				this.orderData.goods_num = 0;
				return;
			}

			let sku_array = [],
				goodsIds = [];

			Object.keys(this.goodsData).forEach(key => {
				let item = this.goodsData[key];
				let skuData = {
					sku_id: item.sku_id,
					num: item.num,
					card_item_id: item.item_id ? item.item_id : 0,
					money: item.money ? item.money : 0 // 无码商品价格
				}
				if (item.is_adjust) {
					skuData.price = item.price; // 手动调整价格
				}
				if (item.goods_money) skuData.goods_money = item.goods_money;
				sku_array.push(skuData)
				if (!item.item_id) goodsIds.push(item.goods_id);
			})
			this.goodsIds = goodsIds;
			let data = {
				sku_array: JSON.stringify(sku_array),
				create_time: this.orderData.create_time
			};
			if (this.memberInfo) data.member_id = this.memberInfo.member_id;

			this.$api.sendRequest({
				url: '/cashier/storeapi/cashierordercreate/calculate',
				data: data,
				success: res => {
					if (res.code == 0) {
						Object.assign(this.orderData, res.data);
						uni.setStorageSync('orderData', this.orderData);
						this.$forceUpdate();
					} else {
						this.$util.showToast({
							title: res.message
						})
					}
				}
			})
		},
		/**
		 * 挂单
		 */
		hangingOrder() {
			if (Object.keys(this.goodsData).length) {
				let data = {
					goods: [],
					order_id: this.orderData.order_id,
					remark: this.orderData.remark
				};
				if (this.memberInfo) data.member_id = this.memberInfo.member_id;
				Object.keys(this.goodsData).forEach(key => {
					let item = this.goodsData[key];
					let skuData = {
						goods_id: item.goods_id,
						sku_id: item.sku_id,
						num: item.num,
						money: item.money ? item.money : 0 // 无码商品价格
					}
					if (item.is_adjust) {
						skuData.price = item.price; // 手动调整价格
					}
					data.goods.push(skuData)
				})
				data.goods = JSON.stringify(data.goods);

				this.$api.sendRequest({
					url: this.orderData.order_id ? '/cashier/storeapi/pendorder/edit' :
						'/cashier/storeapi/pendorder/add',
					data: data,
					success: res => {
						if (res.code == 0) {
							this.orderData.order_id = 0;
							this.wholeOrderCancel();
							this.$refs.order.orderData.page = 0;
							this.$refs.order.getOrder();
						} else {
							this.$util.showToast({
								title: res.message
							})
						}
					}
				})
			} else if (this.orderNum) {
				this.type = 'order';
				this.$refs.order.setHeight();
			} else {
				this.$util.showToast({
					title: '当前没有挂单'
				})
			}
		},
		/**
		 * 取单
		 * @param {Object} data
		 */
		takeorder(data) {
			let goodsData = {};
			data.order_goods.forEach(item => {
				if (item.goods_class == 'money') item.money = item.price;
				goodsData['sku_' + item.sku_id] = item;
			})
			this.goodsData = goodsData;
			this.orderData.order_id = data.order_id;
			this.orderData.goods_list = [];
			this.orderData.remark = data.remark;
			this.calculation();
		},
		/**
		 * 整单取消
		 */
		wholeOrderCancel(isInit = false) {
			if (Object.keys(this.goodsData).length) {
				// 清除当前会员
				this.$refs.member.memberId = 0;
				this.$refs.member.memberCardData.page = 0;
				this.$store.commit('setMemberInfo', null);
				// 清除商品数据
				this.goodsData = {};
				this.calculation();
				if (this.orderData.order_id) {
					this.$refs.order.deleteOrder(this.orderData);
					this.orderData.order_id = 0;
				}
				// 清除订单数据
				this.orderData = {
					goods_num: 0,
					pay_money: 0,
					goods_list: [],
					remark: '',
					create_time: this.$util.timeFormat(parseInt(new Date().getTime() / 1000))
				}
				this.outTradeNo = '';
				this.orderId = 0;
			} else {
				if (!isInit) this.$util.showToast({
					title: '当前没有订单'
				})
			}
		},
		remarkConfirm() {
			this.orderData.remark = this.remark;
			this.$refs.remarkPopup.close();
		},
		/**
		 * 支付
		 */
		pay(type = '', callback) {
			if (!Object.keys(this.goodsData).length || this.isRepeat) return;
			this.isRepeat = true;

			if (this.outTradeNo) {
				this.type = 'pay';
				if (type) this.$refs.payment.type = type;
				return;
			}

			this.pageActive = 'OrderCreate'; // 记录页面活跃值：创建订单

			let sku_array = [];
			Object.keys(this.goodsData).forEach(key => {
				let item = this.goodsData[key];
				let skuData = {
					sku_id: item.sku_id,
					num: item.num,
					card_item_id: item.item_id ? item.item_id : 0,
					money: item.money ? item.money : 0 // 无码商品价格
				};
				if (item.is_adjust) {
					skuData.price = item.price; // 手动调整价格
				}
				sku_array.push(skuData)
			})
			let data = {
				sku_array: JSON.stringify(sku_array),
				remark: this.orderData.remark,
				create_time: this.orderData.create_time
			};
			if (this.memberInfo) data.member_id = this.memberInfo.member_id;

			this.$api.sendRequest({
				url: '/cashier/storeapi/cashierordercreate/create',
				data: data,
				success: res => {
					this.isRepeat = false;
					if (res.code == 0) {
						this.outTradeNo = res.data.out_trade_no;
						this.orderId = res.data.order_id;
						this.type = 'pay';
						if (type) this.$refs.payment.type = type;
						setTimeout(() => {
							if (callback) callback();
						}, 100)
					} else {
						this.$util.showToast({
							title: res.message,
						})
					}
				}
			})
		},
		cancelPayment() {
			if (!this.orderId) return;
			if (this.isRepeat) return;
			this.isRepeat = true;
			this.$api.sendRequest({
				url: '/cashier/storeapi/cashierorder/deleteorder',
				data: {
					order_id: this.orderId
				},
				success: res => {
					if (res.code == 0) {
						this.outTradeNo = '';
						this.orderId = 0;
						this.type = 'goods';
					} else {
						this.$util.showToast({
							title: res.message,
						})
					}
					this.isRepeat = false;
				}
			})
		},
		paySuccess() {
			this.type = 'goods';
			this.wholeOrderCancel();
			this.searchText = '';
			this.$refs.goods.getGoods();
		},
		// nc-goods组件，商品操作
		activeGoods(action) {
			this.pageActive = action;
		},
		// 监听结算组件的活动
		activePayment(active) {
			if (active == 'relieveScanTrigger') {
				// 扫码枪解除键盘占用
				this.isScanTrigger = false;
			}
		},
		// 获取商品信息通过条形码
		getSkuBycode(code) {
			if (this.type != 'goods' || (this.$refs.selectMember && this.$refs.selectMember.popupShow)) return;
			code = code.toString().trim()

			this.$api.sendRequest({
				url: '/cashier/storeapi/goods/skuinfo',
				data: {
					sku_no: code
				},
				success: res => {
					if (res.code == 0) {
						if (res.data) {
							if (res.data.stock == 0) {
								this.$util.showToast({
									title: '该商品库存不足！'
								})
								return;
							}
							this.selectGoods(res.data)
						} else {
							this.$util.showToast({
								title: '未找到该商品！'
							})
						}
					} else {
						this.$util.showToast({
							title: res.message,
						})
					}
				}
			})
		},
		// 调整商品价格，数量
		callBox(data) {
			data.status = 'edit'; // 调整商品标识
			this.$refs.goods.goodsSelect(data);
		},
		/**
		 * 添加扫码监听事件
		 */
		addScancodeEvent() {
			// #ifdef APP-PLUS
			plus.key.addEventListener('keyup', this.listenerScancode, true);
			// #endif

			// #ifdef H5
			window.addEventListener('keypress', this.listenerScancode, true);

			window.addEventListener("keydown", this.listenerKeyDown, true);

			window.addEventListener("focus", this.listenerFocus, true);

			// 监听F1~F12，BACKSPACE
			window.POS_HOTKEY_CALLBACK = (control, code) => {
				this.posHotKeyCallback(code);
			};
			// #endif

		},
		/**
		 * 移除扫码监听事件
		 */
		removeScancodeEvent() {
			// #ifdef APP-PLUS
			plus.key.removeEventListener('keyup', this.listenerScancode, true);
			// #endif

			// #ifdef H5
			window.removeEventListener('keypress', this.listenerScancode, true);

			window.removeEventListener("keydown", this.listenerKeyDown, true);

			window.removeEventListener("focus", this.listenerFocus, true);

			delete window.POS_HOTKEY_CALLBACK;
			// #endif
		},
		/**
		 * 监听扫码事件
		 * @param {Object} e
		 */
		listenerScancode(e) {
			const clearBarCode = () => {
				this.scanCode = {
					lastTime: 0,
					code: ''
				}
				this.isScanTrigger = false;
			}

			// #ifdef H5
			var currCode = e.keyCode || e.which || e.charCode;
			// #endif

			// #ifdef APP-PLUS
			const keycode = ['keycode_7': 0, 'keycode_8': 1, 'keycode_9': 2, 'keycode_10': 3, 'keycode_11': 4,
				'keycode_12':
				5, 'keycode_13': 6, 'keycode_14': 7, 'keycode_15': 8, 'keycode_16': 9
			];
			var currCode = keyArr['keycode_' + e.keyCode] || '';
			// #endif 

			var currTime = new Date().getTime();
			if (this.scanCode.lastTime > 0) {
				if (currTime - this.scanCode.lastTime <= 100) {
					this.scanCode.code += String.fromCharCode(currCode);
					this.isScanTrigger = true;
				} else if (currTime - this.scanCode.lastTime > 500) {
					// 输入间隔500毫秒清空
					clearBarCode();
				}
			} else {
				this.scanCode.code = String.fromCharCode(currCode);
			}
			this.scanCode.lastTime = currTime;

			// #ifdef H5
			var code = 13;
			// #endif

			// #ifdef APP-PLUS
			var code = 66;
			// #endif

			if (currCode == code) {

				// 扫码枪
				if (this.scanCode.code && this.scanCode.code.length >= 8) {
					this.getSkuBycode(this.scanCode.code)
					this.isScanTrigger = true;
				}

				// 回车输入后清空
				clearBarCode();
			}

		},
		// 监听焦点事件
		listenerFocus(e) {
			if (this.pageActive == 'OrderCreate') return;

			let tab = {
				// 聚焦 获取商品选择
				TabGoodsFocus: {
					className: 'goods-select-focus',
					focusField: 'rightIndexFocus'
				},
				// 聚焦 获取订单结算商品
				TabOrderFocus: {
					className: 'settlement-select-focus',
					focusField: 'leftIndexFocus'
				}
			};

			for (let key in tab) {
				if (e.target.className && e.target.className.indexOf(tab[key].className) != -1) {
					this.leftIndexFocus = -1;
					this.rightIndexFocus = -1;
					for (let i = 0; i < e.target.attributes.length; i++) {
						var item = e.target.attributes[i];
						if (item.name == 'data-tab-index') {
							this[tab[key].focusField] = parseInt(item.value);
							break;
						}
					}
					if (this[tab[key].focusField] > -1) {
						this.pageActive = key;
					}
				}

			}

		},
		// 监听键盘按下事件
		listenerKeyDown(e) {
			var code = e.code;

			if (code == 'Tab') return;

			// console.log('KeyDown', this.type, code, this.pageActive, this.isScanTrigger, this.orderData, e);
			// console.log('this.$refs.goods', this.$refs.goods.type);

			// 按键ESC，解除占用
			if (this.isScanTrigger && code == 'Escape') this.isScanTrigger = false;

			// 正在输入商品编码 商品/项目名称
			if (this.pageActive == 'inputSkuNo' || this.pageActive == 'inputSearchText') return;

			// 关闭商品弹出框
			if (code == 'Escape' && this.pageActive == 'SelectGoodsSku' && this.type == 'goods') {
				this.pageActive = 'SelectGoodsAfter';
				return;
			}

			// 多次输入无码商品
			if (this.pageActive == 'SelectGoodsAfter' && this.type == 'goods' && this.$refs.goods && this.$refs.goods
				.type == 'money' && (code != 'Enter' && code != 'NumpadEnter') && (code == 'NumpadDecimal' || code
					.indexOf('Numpad') != -1 || code.indexOf('Digit') !=
					-1)) {
				this.pageActive = 'UnnumberedGoods';
			}

			if (this.type != 'pay' && this.pageActive != 'SelectGoodsSku' && code == 'KeyM') {
				// 选择会员，键盘快捷键【M】
				if (this.$refs.selectMember) {
					this.pageActive = 'ShowMember';
					this.$refs.selectMember.open(() => {
						this.pageActive = 'ShowMemberAfter';
					});
				}

			} else if (['ShowMember', 'ShowMemberCard'].indexOf(this.pageActive) != -1) {
				// 打开会员弹出框

				this.memberCallback(code);

			} else if (this.pageActive == 'ShowMemberAfter') {
				// 活跃窗口：设置会员后

				if (code == 'Enter' || code == 'NumpadEnter') {
					this.pay('');
				}

			} else if (this.pageActive == 'ShowMemberCardAfter') {
				// 活跃窗口：选择会员卡项的服务/商品

				if (code == 'Enter' || code == 'NumpadEnter') {
					if (this.$refs.member) {
						if (this.$refs.member.active == '') {
							// 允许结账
							this.pay('');
						} else {
							this.$refs.member.selectGoods();
						}
					}
				}

			} else if (this.type == 'goods' && code == 'PageUp') {
				// 切换左侧焦点
				this.pageActive = 'TabOrderFocus'
				this.leftIndexFocus = 0;
				this.rightIndexFocus = -1;
				code = 'ArrowUp';
			} else if (this.type == 'goods' && code == 'PageDown') {
				// 切换右侧焦点
				this.pageActive = 'TabGoodsFocus'
				this.rightIndexFocus = 0;
				this.leftIndexFocus = -1;
				code = 'ArrowLeft';
			} else if (this.pageActive == 'UnnumberedGoods' && this.type == 'goods') {
				// 无码商品

				if (code == 'Enter' || code == 'NumpadEnter') {

					if (this.$refs.goods && !this.isScanTrigger) this.$refs.goods.paymentMoneyConfirm();

				}
				// else if (code == 'NumpadDecimal') {

				// 	if (this.$refs.goods) this.$refs.goods.keydown('.');

				// } else if (code.indexOf('Numpad') != -1) {

				// 	var num = code.replace('Numpad', '')
				// 	if (this.$refs.goods) this.$refs.goods.keydown(num);

				// } else if (code.indexOf('Digit') != -1) {

				// 	var num = code.replace('Digit', '')
				// 	if (this.$refs.goods) this.$refs.goods.keydown(num);

				// }

			} else if (this.pageActive == 'SelectGoodsSku' && this.type == 'goods') {

				// 打开商品规格项弹出框
				if (code == 'Enter' || code == 'NumpadEnter') {
					if (this.$refs.goods) this.$refs.goods.skuConfirm();
				}

			} else if (this.pageActive == 'TabGoodsFocus') {
				// 使用tab键，聚焦选择商品

				this.tabGoodsFocusCallback(code);

			} else if (this.pageActive == 'TabOrderFocus') {
				// 使用tab键，聚焦获取订单结算商品

				this.tabOrderFocusCallback(code);

			} else if (this.orderData.goods_num && this.pageActive == 'SelectGoodsAfter' && !this.isScanTrigger) {
				// 选择完商品后

				if (code == 'Enter' || code == 'NumpadEnter') {
					this.pay('');
				}

			}

			// 正在使用扫码枪，禁用键盘
			if (this.isScanTrigger) return;

			if (this.pageActive == 'OrderCreate') {
				// 创建订单

				this.orderCreateCallback(code);

			}

		},
		/**
		 * 监听键盘事件回调
		 * @param {Object} code
		 */
		posHotKeyCallback(code) {
			// console.log('POS ${code} 按键', code, this.type);

			if (code == 'F2') {
				// 选择商品

				if (this.type != 'pay') {
					this.type = 'goods';
					this.pageActive = 'SelectGoodsAfter';
				}

			} else if (code == 'F3') {
				// 挂/取单

				if (this.type != 'pay') {
					this.hangingOrder();
				}

			} else if (code == 'F4') {
				// 选择会员

				if (this.type != 'pay') {
					this.showMember();
				}

			} else if (code == 'F5') {
				// 选择会员卡项

				if (this.type != 'pay') {
					this.showMemberCard();
				}

			} else if (code == 'F12') {
				// 整单取消

				if (this.type != 'pay') {
					this.wholeOrderCancel();
				}

			} else if (code == 'BACKSPACE') {
				// 退格键

				if (this.pageActive == 'UnnumberedGoods' && this.type == 'goods') {

					if (this.$refs.goods) this.$refs.goods.deleteCode();

				} else if (this.pageActive == 'OrderCreate') {

					if (this.$refs.payment) {
						if (this.$refs.payment.active == 'OpenMoneyPopup') {
							this.$refs.payment.deleteCode();
						}
					}

				}

			} else if (code == 'X') {
				// 打开钱箱，快捷键：Alt+X
				this.openCashBox();
			} else if (this.type == 'goods' && code == 'PAGEUP') {
				// 切换左侧焦点
				this.pageActive = 'TabOrderFocus'
				this.leftIndexFocus = 0;
				this.rightIndexFocus = -1;
				this.tabOrderFocusCallback('ArrowUp');
			} else if (this.type == 'goods' && code == 'PAGEDOWN') {
				// 切换右侧焦点
				this.pageActive = 'TabGoodsFocus'
				this.rightIndexFocus = 0;
				this.leftIndexFocus = -1;
				this.tabGoodsFocusCallback('ArrowLeft');
			} else {
				// 触发左侧菜单按键回调
				this.menuTriggerKeyCodeCallBack(code);
			}
		},
		// 打开钱箱
		openCashBox() {
			try {
				let data = {
					message: '打开钱箱'
				};
				POS_.send('OpenCashBox', JSON.stringify(data));
			} catch (e) {
				console.log('打开钱箱异常', e)
			}
		},
		/**
		 * 打开会员弹出框 事件回调
		 * @param {string} code 按键代码
		 */
		memberCallback(code) {
			var showMemberTab = ['ShowMember', 'ShowMemberCard'];

			if (showMemberTab.indexOf(this.pageActive) != -1) {
				let index = showMemberTab.indexOf(this.pageActive);
				let selectMember = this.$refs.selectMember;

				// 选择会员，回车确认
				if (code == 'Enter' || code == 'NumpadEnter') {
					if (selectMember && selectMember.memberId && selectMember.active == 'SearchMember') {
						selectMember.getMemberInfo(selectMember.memberId, () => {
							this.pageActive = showMemberTab[index] + 'After';
						});
					}
				}
			}
		},
		/**
		 * 快捷下单 事件回调
		 * @param {string} code 按键代码
		 */
		quickOrderCallback(code) {
			if (!this.orderData.goods_num) return;

			if (!this.$refs.payment) return;

			let payment = this.$refs.payment;

			// 不能存在操作
			if (payment.active) return;

			// 快捷支付，KeyN：付款码支付，KeyC：现金支付（cash），KeyW：微信支付（wechat），A：支付宝支付（alipay），KeyP：POS刷卡支付（POS）
			payment.hotKeyPay(code, this.type, () => {
				this.pay('', () => {
					payment.hotKeyPayCallback(code);
				});
			});

		},
		/**
		 * 订单创建 事件回调
		 * @param {string} code 按键代码
		 */
		orderCreateCallback(code) {
			if (!this.$refs.payment) return;

			let payment = this.$refs.payment;

			// 快捷支付，KeyN：付款码支付，KeyC：现金支付（cash），KeyW：微信支付（wechat），A：支付宝支付（alipay），KeyP：POS刷卡支付（POS）
			let letterCode = ['KeyN', 'KeyC', 'KeyW', 'KeyA', 'KeyP'];

			if (code == 'KeyM') {
				// 会员码

				payment.switchMemberCode();

			} else if (letterCode.indexOf(code) != -1) {
				// 快捷下单

				this.quickOrderCallback(code);

			} else if (code == 'Escape') {
				// 取消支付，回到上一步，检测当前没有弹出框

				if (payment.active == '') {

					payment.cancelPayment();
					this.pageActive = 'SelectGoodsAfter';

				}

			} else if (payment.active == 'OpenMoneyPopup') {

				if (code == 'Enter' || code == 'NumpadEnter') {

					if (payment.moneyPopup.type == 'reduction') {
						// 减免金额

						payment.moneyPopupConfirm();

					} else if (payment.moneyPopup.type == 'cash') {
						// 现金支付

						payment.moneyPopupConfirm(() => {
							payment.confirm();
						});

					}

				} else if (code == 'NumpadDecimal') {

					payment.keydown('.');

				} else if (code.indexOf('Numpad') != -1) {

					var num = code.replace('Numpad', '')
					payment.keydown(num);


				} else if (code.indexOf('Digit') != -1) {

					var num = code.replace('Digit', '')
					payment.keydown(num);

				}

			} else if (code == 'Enter' || code == 'NumpadEnter') {

				if (payment.paystatus == 'success') {
					// 支付成功

					payment.paySuccess();
					this.pageActive = '';

				} else if (payment.active == 'RemarkPopup') {
					// 备注

					payment.remarkConfirm();

				} else if (payment.active == 'safeVerifyPopup') {
					// 使用付款码，出示付款码、验证手机号

					setTimeout(() => {
						// 打开付款码，设置焦点
						payment.scancodeFocus = true;
					}, 200);

					if (payment.safeVerifyType == 'payment_code') {

						payment.verifyPaymentCode({
							detail: {
								value: payment.paymentCode
							}
						});

					} else if (payment.safeVerifyType == 'sms_code') {

						payment.verifySmsCode({
							detail: {
								value: payment.smsCode
							}
						});

					}

				} else if (payment.active == 'memberCodePopup') {
					// 使用付款码，出示付款码、使用余额

					setTimeout(() => {
						// 打开付款码，设置焦点
						payment.scancodeFocus = true;
					}, 200);

					payment.verifyPaymentCode({
						detail: {
							value: payment.paymentCode
						}
					});

				} else if (payment.active == 'thirdConfirm') {
					// 打开付款码，设置焦点

					setTimeout(() => {
						// 打开付款码，设置焦点
						payment.scancodeFocus = true;
					}, 200);

				} else if (payment.type == 'cash') {

					// 选择【现金支付】方式，打开现金支付弹出框
					if (payment.active == '') {
						payment.switchPayType(payment.type);
					}

				} else if (payment.type != 'third') {
					payment.confirm();
				} else if (payment.active == '') {
					// 付款码/扫码枪

					payment.thirdConfirm();
					setTimeout(() => {
						// 初次打开，设置焦点
						payment.scancodeFocus = true;
					}, 200);

				}
			}
		},
		/**
		 * 使用tab键，聚焦选择商品 事件回调
		 * @param {string} code 按键代码
		 */
		tabGoodsFocusCallback(code) {
			if (!this.$refs.goods) return;

			let list = document.querySelectorAll(`.${this.$refs.goods.type}-focus.table-item`);

			if (code == 'Enter' || code == 'NumpadEnter') {

				if (this.$refs.goods.type == 'goods') {
					// 添加实物商品
					this.$refs.goods.goodsSelect(this.$refs.goods.goodsData.list[this.rightIndexFocus]);
				} else if (this.$refs.goods.type == 'service') {
					// 添加项目商品
					this.$refs.goods.goodsSelect(this.$refs.goods.serviceData.list[this.rightIndexFocus]);
				}

			} else if (code == 'ArrowUp' && this.rightIndexFocus > -1) {

				// 上箭头，商品，goods，项目：service
				const query = uni.createSelectorQuery().in(this);
				query.select(`.goods-container .list-wrap.${this.$refs.goods.type}`).boundingClientRect(data => {
					this.rightIndexFocus -= Math.floor(data.width / 200); // 单个元素宽度200

					// 超出，选择第一个
					if (this.rightIndexFocus <= 0) this.rightIndexFocus = 0;

					list[this.rightIndexFocus].focus();
				}).exec();

			} else if (code == 'ArrowDown' && this.rightIndexFocus > -1) {

				// 下箭头，商品，goods，项目：service
				const query = uni.createSelectorQuery().in(this);
				query.select(`.goods-container .list-wrap.${this.$refs.goods.type}`).boundingClientRect(data => {
					this.rightIndexFocus += Math.floor(data.width / 200); // 单个元素宽度200

					// 超出，选择最后一个
					if (this.rightIndexFocus >= list.length) this.rightIndexFocus = list.length - 1;

					list[this.rightIndexFocus].focus();
				}).exec();

			} else if (code == 'ArrowRight' && this.rightIndexFocus > -1) {

				// 右箭头
				if (this.rightIndexFocus + 1 >= list.length) return;
				this.rightIndexFocus++;

				list[this.rightIndexFocus].focus();

			} else if (code == 'ArrowLeft' && this.rightIndexFocus > -1) {

				// 左箭头
				if (this.rightIndexFocus <= 0) return;
				this.rightIndexFocus--;

				list[this.rightIndexFocus].focus();

			}
		},
		/**
		 * 使用tab键，聚焦 获取订单结算商品 事件回调
		 * @param {string} code 按键代码
		 */
		tabOrderFocusCallback(code) {
			// 按键回车，弹框调整商品数量，注意，此时只能修改商品数量，不能更改规格
			if (code == 'Enter' || code == 'NumpadEnter') {
				let data = this.$util.deepClone(this.orderData.goods_list[this.leftIndexFocus]);
				data.status = 'edit'; // 修改商品数量标识

				if (this.$refs.goods) this.$refs.goods.goodsSelect(data);
			} else if (code == 'ArrowUp' && this.leftIndexFocus > -1) {

				// 上箭头
				let list = document.querySelectorAll(`.settlement-select-focus`);
				if (this.leftIndexFocus <= 0) return;
				this.leftIndexFocus--;
				list[this.leftIndexFocus].focus();

			} else if (code == 'ArrowDown' && this.leftIndexFocus > -1) {

				// 下箭头
				let list = document.querySelectorAll(`.settlement-select-focus`);
				if (this.leftIndexFocus + 1 >= list.length) return;
				this.leftIndexFocus++;
				list[this.leftIndexFocus].focus();

			} else if (code == 'Delete' && this.leftIndexFocus > -1) {
				this.deleteGoods(this.orderData.goods_list[this.leftIndexFocus]);
			}
		},
		// 恢复焦点下标
		restoreFocus() {
			this.leftIndexFocus = -1;
			this.rightIndexFocus = -1;
		}
	},
	computed: {
		orderNum() {
			return this.$store.state.pendOrderNum;
		}
	},
	watch: {
		$route(to, from) {
			if ((to.path == '/pages/billing/index' || to.path == '/') && this.$refs.member && this.memberInfo) {
				this.$refs.member.memberCardData.page = 0;
				this.$refs.member.memberCardData.list = [];
				this.$refs.member.memberCardData.total = 1;
				this.$refs.member.getMemberCard();
			}
		},
		type: function(nVal) {
			if (nVal != 'member') {
				this.$refs.member.search = false;
			}
		},
		orderNum: function(nVal) {
			if (nVal == 0) this.type = 'goods';
		},
		memberInfo: function(nVal, oVal) {
			if ((!this.orderData.order_id && nVal && oVal && nVal.member_id != oVal.member_id) || !nVal) {
				this.goodsData = {};
			}
			this.calculation();
		},
		pageActive(nVal) {
			if (nVal == 'SelectGoodsAfter') {
				this.rightIndexFocus = -1; // 选择完商品后，取消选中焦点
			}
		}
	}
}